package cn.com.ddapp.ddm.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import cn.com.ddapp.ddm.MainActivity;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.bean.AdEntitiy;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TDevice;
import cn.com.ddapp.ddm.util.TLog;


public class AdActivity extends Activity {
    private static final String ISSTART ="ISSTART";
    @BindView(R.id.view_pager)
    ViewPager view_pager;
    private ArrayList<String> list = new ArrayList<String>();
    private LinearLayout dot_layout;
    private int[] imgDrw = new int[] { R.mipmap.dot_normal, R.mipmap.w_vip};
    ImageView tv_des;
    LinearLayout toMain;
    protected Gson gson = new Gson();
    private  AdEntitiy entity;
    private MyPagerAdapter myPagerAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);

//        final AlphaAnimation aa = new AlphaAnimation(1.0f,0.8f);
//        ScaleAnimation ss=new ScaleAnimation(1.0f,0.5f);
//        aa.setDuration(2000);
//        aa.setFillAfter(true);
//        start_ll.startAnimation(aa);
//        aa.setAnimationListener(new Animation.AnimationListener()
//        {
//            @Override
//            public void onAnimationEnd(Animation arg0) {
//                redirectTo();
//            }
//            @Override
//            public void onAnimationRepeat(Animation animation) {}
//            @Override
//            public void onAnimationStart(Animation animation) {}
//
//        });
        TimerTask task = new TimerTask(){

            public void run(){

                //execute the task
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
                finish();
            }

        };

        Timer timer = new Timer();

        timer.schedule(task, 2000);

        if(TDevice.isTablet(AdActivity.this)){
//            if (SPUtils.getBooleanData(StartActivity.this, SPUtils.ISFIRST)) {
                    startIntent(AdActivity.this,MainActivity.class);
                    finish();
//            } else {
//                setContentView(R.layout.activity_start);
//                initVieww();
//            }
            Log.i("aaa","--is-"+TDevice.isTablet(AdActivity.this));
        }else{
             requestData();
//            if (SPUtils.getBooleanData(AdActivity.this, SPUtils.ISFIRST)) {
//                startIntent(AdActivity.this,FirstStartActivity.class);
//                finish();
//            } else {
            myPagerAdapter = new MyPagerAdapter();
                setContentView(R.layout.activity_start);
                initVieww();
//            }
            Log.i("aaa","--in-"+TDevice.isTablet(AdActivity.this));
        }
        super.onCreate(savedInstanceState);
    }


    private void requestData() {


        final OkUtilCallback okUtilCallback =  new OkUtilCallback() {
            @Override
            public void onMyResponse(String response, int id) {
                TLog.log(response);
                entity  = gson.fromJson(response,AdEntitiy.class);
                list.addAll(entity.getList());
                myPagerAdapter.notifyDataSetChanged();
//                if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))&&entity.getLogin()){
////                    mEmptyLayout.setErrorType(EmptyLayout.NO_LOGIN);
//                }else if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
//                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.CENTER);
//                }else {
//                    ReturnDetail returnDetail = entity.getReturnDetail();
//                    fundAmount.setText(""+returnDetail.getReturnAmount());
//                    fundTime.setText(returnDetail.getSuccessTime());
//                    rtType.setText(returnDetail.getReturnType());
//                    rtAmount.setText(""+returnDetail.getReturnAmount());
//                    rtReason.setText(returnDetail.getContent());
//                    rtRemark.setText(returnDetail.getReson());
//                    rtNo.setText(returnDetail.getExpressNo());
//                    rtTime.setText(returnDetail.getCreateTime());
//                }

            }
        };
        OKUtilAPI.post(OKUtilAPI.ADList, "", okUtilCallback);
    }


    public static void startIntent(Context context, Class class1) {
        Intent intent = new Intent(context, class1);
        context.startActivity(intent);
    }
    private LinearLayout ll_focus_indicator_container;
    private ViewPager mPager;
    public int getDS(int dp){
       return (int) (getResources().getDisplayMetrics().density*dp);
    }
    class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
			return list.size();
        }

        /**
         * 判断instantiateItem方法返回的是否是view对象
         */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }

        /**
         * 相当于BaseAdapter的getView方法,创建page的方法
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = View.inflate(AdActivity.this, R.layout.adapter_ad, null);
            ImageView image = (ImageView) view.findViewById(R.id.image);
//            image.setImageResource(list.get(position).getIconResId());
            Glide.with(getApplicationContext()).load(OKUtilAPI.imgBaseUrl+list.get(position)).into(image);
            //将view添加到VIewPager中

            container.addView(view);
            return view;
        }
        /**
         * 销毁view对象的
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//			super.destroyItem(container, position, object);//这个要去掉，因为会抛出异常
            container.removeView((View) object);
        }
    }

    /**
     * 更新描述和点
     */
    private void updateDesAndDot(){
        int currentPage = view_pager.getCurrentItem();//获取当前是第几页
        //设置描述信息
        //更改点的状态
//        for (int i = 0; i < dot_layout.getChildCount(); i++) {
////			if(i==currentPage){
////				dot_layout.getChildAt(i).setEnabled(true);
////			}else {
////				dot_layout.getChildAt(i).setEnabled(false);
////			}
//
//            dot_layout.getChildAt(i).setEnabled(i==currentPage);
//        }
    }

//    private void initDot(){
//        for (int i = 0; i < list.size(); i++) {
//            View view = new View(this);
//            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(getDS(12), getDS(12));
//            params.leftMargin =10;
//            view.setLayoutParams(params);
//            view.setBackgroundResource(R.drawable.selector_dot);
//            dot_layout.addView(view);
//        }
//    }

    private void initVieww() {
        view_pager = (ViewPager) findViewById(R.id.view_pager);
        dot_layout = (LinearLayout) findViewById(R.id.dot_layout);
        tv_des = (ImageView) findViewById(R.id.tv_des);
        toMain= (LinearLayout) findViewById(R.id.toMain);
        //2.准备数据
//        list.add(new Ad(R.mipmap.stone, "a"));
//        list.add(new Ad(R.mipmap.sttwo, "b"));
//        list.add(new Ad(R.mipmap.stthree, "c"));
        //3.绑定数据到ViewPager
        view_pager.setAdapter(myPagerAdapter);
        view_pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            /**
             * 只有当page改变的时候会回调该方法
             */
            @Override
            public void onPageSelected(int position) {
                updateDesAndDot();
                if(position==2){
                    tv_des.setVisibility(View.VISIBLE);
                    toMain.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SPUtils.setBooleanData(AdActivity.this,SPUtils.ISFIRST,true);
                            startIntent(AdActivity.this,MainActivity.class);
                            finish();
                        }
                    });
                }
                else{
                    tv_des.setVisibility(View.INVISIBLE);
                }
            }
            /**
             * 当page滑动的时候会一直回调
             */
            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
//				Log.e("tag", "onPageScrolled: ");
            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
//        initDot();
        updateDesAndDot();
    }
}
